package aliyun.cx.service.service.impl;

import aliyun.cx.service.entity.SysConfig;
import aliyun.cx.service.mapper.SysConfigMapper;
import aliyun.cx.service.service.SysConfigService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * 系统配置Service实现类
 */
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements SysConfigService {

    @Override
    @Cacheable(value = "sysConfig", key = "#configKey")
    public String getConfigValue(String configKey) {
        LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysConfig::getConfigKey, configKey);
        SysConfig config = this.getOne(wrapper);
        return config != null ? config.getConfigValue() : null;
    }

    @Override
    @Cacheable(value = "sysConfig", key = "#configKey")
    public String getConfigValue(String configKey, String defaultValue) {
        String value = getConfigValue(configKey);
        return value != null ? value : defaultValue;
    }

    @Override
    @CacheEvict(value = "sysConfig", key = "#configKey")
    public boolean setConfigValue(String configKey, String configValue) {
        LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysConfig::getConfigKey, configKey);
        SysConfig config = this.getOne(wrapper);
        
        if (config != null) {
            config.setConfigValue(configValue);
            return this.updateById(config);
        } else {
            // 如果配置不存在，创建新配置
            config = new SysConfig();
            config.setConfigKey(configKey);
            config.setConfigValue(configValue);
            config.setConfigName(configKey);
            config.setConfigType("string");
            config.setIsSystem(false);
            return this.save(config);
        }
    }

    @Override
    @CacheEvict(value = "sysConfig", allEntries = true)
    public void refreshConfigCache() {
        // 清除所有配置缓存
    }
}
